const nameInitialState = {
    data :  [],
    copyData : [],
    loading : true
}
const reduce = (state = nameInitialState, {type,payload}) => {
    const newState = JSON.parse(JSON.stringify(state))
    switch (type) {
        case "GET_LIST":
          
            newState.data = payload.data
            newState.copyData = payload.data
            newState.loading  = payload.loading
    
            return newState 
        case 'DEL_ITEM':

            newState.data.forEach((item,index) => {
                if(item.id === payload.id) {
                    newState.data.splice(index, 1)
                }
            })
      
            return newState 
        case 'SET_DATA':

            newState.data.push(payload)
      
            return newState 

        case 'EDIT_DATA':  //编辑
            newState.data.forEach((item) => {
                if(item.id === payload.id) {
                    item.name = payload.name
                    item.city = payload.city
                }
            })
            
            return newState 


        case 'FILTER_DATA':  //筛选
            newState.data = newState.copyData.filter((item) => {
                return item.type === payload || item.name.includes(payload)
            })
            
            return newState 

        case 'ALL_DELETE':  //批量删除

           for (let i = newState.data.length - 1; i >= 0  ; i--) {
              for (let j = 0; j < payload.length; j++) {
                if(newState.data[i].key === payload[j].key) {
              
                     newState.data.splice(i,1)   
                  
                }  
              }
           }

            return newState 
        default:
            return newState 
    }
}

export default reduce